package com.yhy.common.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 20-3-31 下午8:03 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2020<br>
 *  *
 *
 */
public class QrBarcodeUtil {
    private static final String UTF8_CODE = "utf-8";
    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 条形码宽度
     */
    private static final int DFT_BARCODE_WIDTH = 200;

    /**
     * 条形码高度
     */
    private static final int DFT_BARCODE_HEIGHT = 50;

    /**
     * 加文字 条形码
     */
    private static final int DFT_BARCODE_WORDHEIGHT = 50;

    private static final int DFT_QRDE_HEIGHT = 200;

    /**
     * 生成RQ二维码
     *
     * @param str    内容
     * @param height 高度（px）
     * @author yanghuiyuan
     */
    public static BufferedImage getRQ(String str, Integer height) {
        if (height == null || height < 100) {
            height = DFT_QRDE_HEIGHT;
        }
        try {
            // 文字编码
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, UTF8_CODE);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str,
                    BarcodeFormat.QR_CODE, height, height, hints);
            //ServletOutputStream out = response.getOutputStream();
            //MatrixToImageWriter.writeToStream(bitMatrix,"png",out);
            return toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成一维码（128）
     *
     * @param str
     * @param width
     * @param height
     * @return
     * @author yanghuiyuan
     */
    public static BufferedImage getBarcode(String str, Integer width,
                                           Integer height) {

        if (width == null || width < DFT_BARCODE_WIDTH) {
            width = DFT_BARCODE_WIDTH;
        }
        if (height == null || height < DFT_BARCODE_HEIGHT) {
            height = DFT_BARCODE_HEIGHT;
        }

        try {
            // 文字编码
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, UTF8_CODE);
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 0);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str,
                    BarcodeFormat.CODE_128, width, height, hints);
            return toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成二维码，写到文件中
     *
     * @param str
     * @param height
     * @param file
     * @throws IOException
     * @author yanghuiyuan
     */
    public static void getQRWriteFile(String str, Integer height, File file) {
        BufferedImage image = getRQ(str, height);
        try {
            ImageIO.write(image, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getQRWriteByte(String str, Integer height, ByteArrayOutputStream out) {
        BufferedImage image = getRQ(str, height);
        try {
            ImageIO.write(image, "png", out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成一维码，写到文件中
     *
     * @param str
     * @param height
     * @param file
     * @throws IOException
     * @author yanghuiyuan
     */
    public static void getBarcodeWriteFile(String str, Integer width,
                                           Integer height, File file) {
        BufferedImage image = getBarcode(str, width, height);
        try {
             ImageIO.write(image, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getBarcodeWriteByte(String str, Integer width,
                                           Integer height, ByteArrayOutputStream outputStream) {
        BufferedImage image = getBarcode(str, width, height);
        try {
            ImageIO.write(image, "png", outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转换成图片
     * @param matrix
     * @return
     * @author yanghuiyuan
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 解码(二维、一维均可)
     */
    public static String read(File file) {

        BufferedImage image;
        try {
            if (file == null || file.exists() == false) {
                throw new Exception(" File not found:" + file.getPath());
            }
            image = ImageIO.read(file);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result;
            // 解码设置编码方式为：utf-8，
            Hashtable hints = new Hashtable();
            hints.put(DecodeHintType.CHARACTER_SET, UTF8_CODE);
            result = new MultiFormatReader().decode(bitmap, hints);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @param image 条形码图片
     * @param words 文字
     * @return 返回BufferedImage
     * @author yanghuiyuan
     */
    public static BufferedImage insertWords(BufferedImage image, String words) {
        // 新的图片，把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {
            BufferedImage outImage = new BufferedImage(DFT_BARCODE_WIDTH, DFT_BARCODE_WORDHEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX = (DFT_BARCODE_WIDTH - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY = DFT_BARCODE_HEIGHT + 20;
            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0, 0, 600, 600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    public static void main(String[] args) throws Exception {
        File file = new File("D://test.png");
        // 生成二维码
        QrBarcodeUtil.getQRWriteFile("http://www.baid.com", 200, file);

        BufferedImage image = QrBarcodeUtil.getBarcode(YhyUtils.genRandom(), null, null);//insertWords(QrBarcodeUtil.getBarcode(YhyUtils.genRandom(), null, null), "12345-6中文测试dsfdsfsdf_789");
        ImageIO.write(image, "png", new File("D://abc.png"));

        // 生成一维码
        //QrBarcodeUtil.getBarcodeWriteFile("6940577300018", null, null, file);
        System.out.println("-----生成成功----");
        System.out.println();

        // 解析生成的图片
        String jxr = QrBarcodeUtil.read(file);

        System.out.println("-----解析成功----");
        System.out.println(jxr);
    }
}
